import Taro, { getCurrentInstance } from '@tarojs/taro'
import store from '../store/index'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import { pageUrl } from './url'

export const redirectTo = (path, params) => {
  Taro.redirectTo({
    url: pageUrl(path, query)
  })
}

export const navigateTo = (path, params) => {
  const query = formatParams(params)
  Taro.navigateTo({
    url: pageUrl(path, query)
  })
}

export const formatParams = params => {
  let query = []
  if (params) {
    for (const index in params) {
      query.push(`${index}=${params[index]}`)
    }
  }
  return query.join('&')
}

export const toast = {
  success: title => toastToPromise(title, 'success'),
  info: title => toastToPromise(title, 'none')
}

export const toastToPromise = (title, icon) => {
  return new Promise(resolve => {
    const duration = 1500
    Taro.showToast({
      title,
      duration,
      icon,
      success: () => {
        setTimeout(resolve, duration)
      }
    })
  })
}

export const call = phoneNumber => {
  Taro.makePhoneCall({
    phoneNumber
  })
}

export const getParam = key => {
  return getCurrentInstance().router.params[key]
}

export const goBack = () => {
  Taro.navigateBack()
}

export const formatTime = time => {
  const difference = new Date().getTime() / 1000 - time
  if (difference < 60) {
    return '刚刚'
  } else if (difference < 3600) {
    return Math.ceil(difference / 60) + '分钟前'
  } else if (difference < 86400) {
    return Math.ceil(difference / 3600) + '小时前'
  } else if (difference < 2592000) {
    return Math.ceil(difference / 86400) + '天前'
  } else if (difference < 86400 * 365) {
    return Math.ceil(difference / 2592000) + '个月前'
  } else {
    return Math.ceil(difference / (86400 * 365)) + '年前'
  }
}

export const compressImage = config => {
  return Taro.compressImage(config)
}

export const formatter = time => {
  const now = new Date(time)
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const date = now.getDate()
  return year + '-' + month + '-' + date
}
export const formatterYearMonth = time => {
  const now = new Date(time)
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  return year + '-' + month
}

export const formatAddress = car_address => {
  return car_address
    .map(item => {
      if (
        ['110000', '120000', '310000', '500000'].includes(
          `${item.province_code}`
        ) ||
        !item.city_code
      ) {
        return item.province_name
      }
      return item.city_name
    })
    .join('、')
}

export const formatTimeOnlyWeek = time => {
  let timeObj
  if (typeof time === 'string') {
    dayjs.extend(customParseFormat)
    timeObj = dayjs(time, 'YYYY-MM-DD HH:mm:ss')
  } else {
    timeObj = dayjs.unix(time)
  }
  const difference = (new Date().getTime() - timeObj.valueOf()) / 1000
  if (difference < 60) {
    return '刚刚'
  } else if (difference < 3600) {
    return Math.ceil(difference / 60) + '分钟前'
  } else if (difference < 86400) {
    return Math.ceil(difference / 3600) + '小时前'
  } else if (difference < 86400 * 7) {
    return Math.ceil(difference / 86400) + '天前'
  } else {
    return timeObj.format('MM-DD')
  }
}

export const fixZero = str => {
  return `00${str}`.substr(-2)
}

export const getMinDate = () => {
  const now = new Date()
  now.setFullYear(now.getFullYear() - 50)
  return now
}

export const getMaxDate = () => {
  const now = new Date()
  now.setFullYear(now.getFullYear() + 50)
  return now
}

export const toLogin = () => {
  const currentRoute = getCurrentInstance().router
  const from = encodeURIComponent(
    currentRoute.path + '?' + formatParams(currentRoute.params)
  )
  Taro.redirectTo({
    url: `/pages/login/index?from=${from}`
  })
}

export const checkPermission = async key => {
  if (!store.state.user.token) {
    toLogin()
    throw new Error('没有登录')
  }
  const permission = store.state.dict.permissions[key]
  if (!permission) {
    throw new Error('没有该权限')
  }
  const notPermissions = []
  for (const value of permission) {
    if (value === '1') {
      return true
    }
    if (value === '100' || value === '1&100') {
      if (store.state.user.userInfo.personal_auth_status) {
        return true
      } else {
        notPermissions.push('100')
      }
    } else if (value === '200' || value === '1&200') {
      if (store.state.user.userInfo.enterprise_certification_status) {
        return true
      } else {
        notPermissions.push('200')
      }
    }
  }

  if (notPermissions.length > 1) {
    Taro.showToast({
      title: '请前往APP完成个人认证或企业认证',
      icon: 'none',
      duration: 2000
    })
  }
  if (notPermissions[0] === '100') {
    Taro.showToast({
      title: '请前往APP完成个人认证或企业认证',
      icon: 'none',
      duration: 2000
    })
  } else if (notPermissions[0] === '200') {
    Taro.showToast({
      title: '请前往APP完成企业认证',
      icon: 'none',
      duration: 2000
    })
  }
  throw new Error('没有权限')
}
